<template>
  <div id="container"></div>

  <!-- 搜索框 -->
  <div class="search-box" v-if="mode === 'createOrder'">
    <el-input
      v-model="searchKeyword"
      placeholder="输入地点关键词"
      clearable
      @input="handleInput"
      @keyup.enter="handleSearch"
    >
      <template #append>
        <el-button :icon="Search" @click="handleSearch" />
      </template>
    </el-input>
    <!-- 建议列表 -->
    <el-card 
      v-show="showSuggestions"
      class="suggestion-list"
      shadow="always"
    >
      <div 
        v-for="item in suggestions" 
        :key="item.id"
        class="suggestion-item"
        @click="handleSelectSuggestion(item)"
      >  
        <div class="title">
          <span v-html="highlightKeyword(item.title)"></span>
        </div>
        <div class="address">{{ item.address || '暂无地址信息' }}</div>
      </div>
      <el-empty v-if="suggestions.length === 0" description="暂无数据" />
    </el-card>
  </div>
</template>

<script setup lang="ts" name="tMap">
import { nextTick, ref, watch } from 'vue';
// import { useMapStore } from '@/stores/useMapStore';
import { useStaffSelectStore } from '@/stores/useStaffSelectStore';
import useSearchPosition from '@/hooks/useSearchPosition';
import { Search } from '@element-plus/icons-vue'

const props = defineProps({
  mode:String
})

const emit = defineEmits(['update:address', 'close'])

const mode = props.mode
const staffSelectStore = useStaffSelectStore()
const TMap = (window as any).TMap
//地图实例
const mapRef = ref<TMap.Map | null>(null)
let markerLayer:any = null
let polylineInstance: any = null

// 处理地图标记点确认
const handleMapConfirm = (place: any) => {
  emit('update:address', place.address)
  emit('close')
}

if(mode==="createOrder"){
  staffSelectStore.setCustomLocation({lat: 34.75469, lng: 113.65717})
  staffSelectStore.setLocation({lat: 34.75469, lng: 113.65717})
}
let customLat = staffSelectStore.customLocation.lat   //顾客位置经纬度
let customLng = staffSelectStore.customLocation.lng
const center = new TMap.LatLng(customLat, customLng);
watch(() => staffSelectStore.resultLocation, () => {
  const lat = staffSelectStore.resultLocation.lat   //员工位置经纬度
  const lng = staffSelectStore.resultLocation.lng
  markerLayer.updateGeometries([
    {
    "id": "from",
    "styleId": 'serviceStaffStyle',
    "position": new TMap.LatLng(lat, lng),
    }
  ])
  polylineInstance.setGeometries([
    {
    "id": "distanceArc",
    'styleId': 'arc',//绑定样式名
    'paths': [center, new TMap.LatLng(lat, lng)]
    }
  ])
})

nextTick(() => {
  mapRef.value = initMap(staffSelectStore.resultLocation.lat, staffSelectStore.resultLocation.lng)
});
//初始化地图
function initMap(lat:string, lng:string) {
  const from = new TMap.LatLng(lat, lng);
  //初始化地图
  const map = new TMap.Map("container", {
    rotation: 20,//设置地图旋转角度
    pitch:30, //设置俯仰角度（0~45）
    zoom:12,//设置地图缩放级别
    center: center//设置地图中心点坐标
  });
  // 点标记数据数组
  const resultLocation = [
    {
      id:'center',
      position:center
    },
    {
      id:'from',
      "styleId": 'serviceStaffStyle',
      position:from
    }
  ]
  const polyline = [
    {
      'id': 'distanceArc',//折线唯一标识，删除时使用
      'styleId': 'arc',//绑定样式名
      'paths': [center, from]
    }
  ]
  if(mode === 'orderInfo'){
    markerLayer = new TMap.MultiMarker({
    map: map,
    styles: {
        // 点标记样式
        marker: new TMap.MarkerStyle({
          width: 20, // 样式宽
          height: 30, // 样式高
          anchor: { x: 10, y: 30 }, // 描点位置
        }),
        "serviceStaffStyle": new TMap.MarkerStyle({ 
          "width": 40,  // 点标记样式宽度（像素）
          "height": 40, // 点标记样式高度（像素）
          "src": '/public/service_position.png',  //图片路径
          //焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
          "anchor": { x: 20, y: 35 }  
        })
      },
      geometries: resultLocation,
    });
  }
  //点标记

  // 初始化弧线
  polylineInstance = new TMap.MultiPolyline({
    id: 'distanceArc',
    map: map,
    styles: {
      arc: new TMap.PolylineStyle({
        color: '#3777FF', // 弧线颜色
        width: 6,          // 线宽
        borderWidth: 5,    // 边框宽度
        borderColor: '#FFF', // 边框颜色
        lineCap: 'round'   // 线端形状
      })
    },
    geometries: polyline
  })
  return map
}
const { searchKeyword, suggestions, showSuggestions, handleInput, highlightKeyword, handleSelectSuggestion, handleSearch  } = useSearchPosition(TMap, mapRef, handleMapConfirm)

</script>

<style scoped>
#container{
  width: 800px;
  height: 500px;
}
.search-box {
  position: absolute;
  top: 41px;
  left: 15px;
  width: 400px;
  z-index: 1000;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.suggestion-list {
  margin-top: 5px;
  max-height: 300px;
  overflow-y: auto;
  background: white;
  z-index: 1001;
  position: relative;
}

.suggestion-item {
  padding: 10px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.suggestion-item:hover {
  background-color: #f5f7fa;
}

.highlight {
  color: #409eff;
  font-weight: bold;
}

.address {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

:deep(.info-window) {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

:deep(.info-window button) {
  transition: background-color 0.3s;
}

:deep(.info-window button:hover) {
  background-color: #66b1ff !important;
}
</style>